
//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/4.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import ReactiveCocoa

class UserAccountViewModel: NSObject {
    
//  单例
    static let sharedUserAccount = UserAccountViewModel()
    
    override init() {
        userAccount = UserAccount.loadUserAccount()
    }
 /// 用户账号
    var userAccount :UserAccount?
    
    var accessToken:String?{
        return userAccount?.access_token
    }
    
    var userLogon: Bool{
        return accessToken != nil
    }
    var avatarUrl:NSURL? {
        return NSURL(string: userAccount?.avatar_large ?? "")
    }
    
// MARK:-----加载网络信息
    func loadUserAccount(code: String)->RACSignal{
        
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            
            NetWorkTools.sharedTools.loadAccesssToken(code).doNext({ (result) -> Void in
                
                let account = UserAccount(dict: result as! [String: AnyObject])
                self.userAccount = account
                printLog(account)
                
               NetWorkTools.sharedTools.loadUserInfo(account.uid!).subscribeNext({ (result) -> Void in
                
                    let dict = result as! [String: AnyObject]
                    account.name = dict["name"] as? String
                    account.avatar_large = dict["avatar_large"] as? String
                    printLog(account)
                    
                    // 保存账号
                    account.saveUserAccount()
                    
                    // 通知订阅者网络数据加载完成
                    subscriber.sendCompleted()
                
                    },error:{(error)->Void in
                        subscriber.sendError(error)
                })
            }).subscribeError({ (error) -> Void in
                subscriber.sendError(error)
            })
            return nil
        })
        
    }
    
    
    
    
    
    

}
